package com.zh.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.common.Result;
import com.zh.entity.User;
import com.zh.service.UserService;
import com.zh.utils.SMSUtils;
import com.zh.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author 你爹
 * @since 2023-09-21
 */
@RestController
@RequestMapping("/user")
@Slf4j
//TODO 优化验证码 已完成
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
//            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //TODO 记得改回来
            String code ="0000";
            log.info("code={}",code);
            //将生成的验证码保存到Redis中，并设置过期时间
            redisTemplate.opsForValue().set("code",code,5, TimeUnit.MINUTES);
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

//            //需要将生成的验证码保存到Session
//            session.setAttribute(phone,code);

            return Result.success("手机验证码短信发送成功");
        }

        return Result.error("短信发送失败");
    }

    /**
     * 移动端用户登录
     * @param map Map
     * @param request HttpServletRequest
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map, HttpServletRequest request){
        HttpSession session = request.getSession();
        log.info(map.toString());

        //获取手机号
        String phone = map.get("phone").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从redis获取保存的验证码
        String codeInRedis = (Objects.requireNonNull(redisTemplate.opsForValue().get("code"))).toString();
        log.info("codeInRedis;{}",codeInRedis);
        //进行验证码的比对（页面提交的验证码和Redis中保存的验证码比对）
        if(codeInRedis != null && codeInRedis.equals(code)){
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            if(user == null){
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                user.setName("降温罩"+ new Random().nextInt(1000));
                user.setSex("男");
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //登录成功从redis删除code
            redisTemplate.delete("code");
            return Result.success(user);
        }
        return Result.error("登录失败");
    }

    @PostMapping("/loginout")
    public Result loginout(HttpSession session){
        log.info("用户登出");
        session.removeAttribute("user");
        return Result.success();
    }

}

